<script lang="ts">
  import { onMount, onDestroy } from 'svelte';
  import { getTaskStatus, getReportUrl, cleanupTask } from '../../lib/api';
  import type { TaskInfo, FrameworkInfo } from '../../lib/types';

  // 组件属性
  export let taskId: string;

  let taskInfo: TaskInfo | null = null;
  let loading = true;
  let error: string | null = null;
  let pollingInterval: number | null = null;
  let taskComplete = false;
  let showDeleteModal = false;
  let isDeleting = false;
  let deleteError: string | null = null;
  let deleteSuccess = false;

  // 分组框架
  let frameworksByCategory: {[key: string]: FrameworkInfo[]} = {};

  // 轮询任务状态
  async function pollTaskStatus() {
    try {
      const status = await getTaskStatus(taskId);
      taskInfo = status;
      
      // 如果任务完成，停止轮询
      if (status.status === 'completed' || status.status === 'failed') {
        taskComplete = true;
        stopPolling();
        
        // 如果有结果，对框架按类别分组
        if (status.status === 'completed' && status.result) {
          const frameworks = status.result.frameworks || [];
          
          // 按类别分组
          frameworksByCategory = frameworks.reduce((groups: {[key: string]: FrameworkInfo[]}, framework: FrameworkInfo) => {
            const category = framework.category || '其他';
            if (!groups[category]) {
              groups[category] = [];
            }
            groups[category].push(framework);
            return groups;
          }, {});
        }
      }
      
      loading = false;
    } catch (e) {
      error = e instanceof Error ? e.message : '获取任务状态失败';
      loading = false;
    }
  }

  // 开始轮询
  function startPolling() {
    pollTaskStatus();
    pollingInterval = setInterval(pollTaskStatus, 3000) as unknown as number;
  }

  // 停止轮询
  function stopPolling() {
    if (pollingInterval !== null) {
      clearInterval(pollingInterval);
      pollingInterval = null;
    }
  }

  // 获取状态标签类
  function getStatusClass(status: string): string {
    switch (status) {
      case 'completed': return 'status-completed';
      case 'failed': return 'status-failed';
      case 'processing': return 'status-processing';
      default: return 'status-pending';
    }
  }

  // 获取报告URL
  function getHtmlReportUrl() {
    return getReportUrl(taskId, 'html');
  }

  function getJsonReportUrl() {
    return getReportUrl(taskId, 'json');
  }

  // 格式化时间
  function formatDateTime(dateTimeStr: string): string {
    try {
      const date = new Date(dateTimeStr);
      return date.toLocaleString('zh-CN');
    } catch (e) {
      return dateTimeStr;
    }
  }

  // 打开删除确认对话框
  function openDeleteModal() {
    showDeleteModal = true;
  }

  // 关闭删除确认对话框
  function closeDeleteModal() {
    showDeleteModal = false;
    deleteError = null;
  }

  // 删除任务文件
  async function handleDelete(includeReports = false) {
    try {
      isDeleting = true;
      deleteError = null;
      
      await cleanupTask(taskId, includeReports, false);
      
      deleteSuccess = true;
      setTimeout(() => {
        showDeleteModal = false;
        if (includeReports) {
          // 如果删除了报告，返回首页
          window.location.href = '/';
        } else {
          // 重新加载任务状态
          pollTaskStatus();
        }
      }, 1500);
    } catch (e) {
      deleteError = e instanceof Error ? e.message : '删除文件失败';
    } finally {
      isDeleting = false;
    }
  }

  // 组件挂载时开始轮询
  onMount(() => {
    startPolling();
  });

  // 组件卸载时停止轮询
  onDestroy(() => {
    stopPolling();
  });
</script>

<svelte:head>
  <title>分析任务 {taskId}</title>
</svelte:head>

<div class="task-container">
  <header>
    <div class="back-link">
      <a href="/">← 返回首页</a>
    </div>
    <h1>应用分析任务</h1>
  </header>

  {#if loading && !taskInfo}
    <div class="loading">
      <div class="spinner"></div>
      <p>正在加载任务信息...</p>
    </div>
  {:else if error}
    <div class="error-card">
      <h2>发生错误</h2>
      <p>{error}</p>
      <button on:click={startPolling}>重试</button>
    </div>
  {:else if taskInfo}
    <div class="task-card">
      <div class="task-header">
        <h2>任务ID: {taskInfo.task_id}</h2>
        <div class="task-meta">
          <div class="status-badge {getStatusClass(taskInfo.status)}">
            {taskInfo.status === 'pending' ? '等待中' : 
             taskInfo.status === 'processing' ? '分析中' : 
             taskInfo.status === 'completed' ? '已完成' : '失败'}
          </div>
          <div class="task-time">
            <div>创建时间: {formatDateTime(taskInfo.created_at)}</div>
            <div>更新时间: {formatDateTime(taskInfo.updated_at)}</div>
          </div>
          
          <!-- 添加删除按钮 -->
          {#if taskInfo.status === 'completed' || taskInfo.status === 'failed'}
            <button class="delete-button" on:click={openDeleteModal}>
              <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <path d="M3 6h18M19 6v14a2 2 0 01-2 2H7a2 2 0 01-2-2V6m3 0V4a2 2 0 012-2h4a2 2 0 012 2v2M10 11v6M14 11v6"></path>
              </svg>
              删除文件
            </button>
          {/if}
        </div>
      </div>

      {#if taskInfo.status === 'processing' || taskInfo.status === 'pending'}
        <div class="progress-section">
          <div class="progress-bar">
            <div class="progress-inner"></div>
          </div>
          <p>正在分析应用，请稍候...</p>
        </div>
      {:else if taskInfo.status === 'failed'}
        <div class="error-section">
          <h3>分析失败</h3>
          <p>{taskInfo.error || '未知错误'}</p>
        </div>
      {:else if taskInfo.status === 'completed' && taskInfo.result}
        <div class="result-section">
          <div class="summary-section">
            <h3>分析结果摘要</h3>
            <pre>{taskInfo.result.summary}</pre>
          </div>

          <div class="frameworks-section">
            <h3>检测到的框架 ({taskInfo.result.frameworks_count})</h3>
            
            {#if taskInfo.result.frameworks_count === 0}
              <p>未检测到任何框架</p>
            {:else}
              {#each Object.entries(frameworksByCategory) as [category, frameworks]}
                <div class="category-group">
                  <h4>{category}</h4>
                  <div class="frameworks-grid">
                    {#each frameworks as framework}
                      <div class="framework-card">
                        <div class="framework-header">
                          <h5>{framework.name}</h5>
                          <div class="confidence-badge" 
                               style="background-color: {framework.confidence > 80 ? '#4caf50' : 
                                                        framework.confidence > 50 ? '#ff9800' : '#f44336'}">
                            {framework.confidence}%
                          </div>
                        </div>
                        <div class="framework-version">版本: {framework.version || '未知'}</div>
                        
                        {#if framework.description}
                          <div class="framework-description">{framework.description}</div>
                        {/if}
                        
                        {#if framework.related_frameworks && framework.related_frameworks.length > 0}
                          <div class="related-frameworks">
                            <strong>相关框架:</strong>
                            <div class="related-list">
                              {#each framework.related_frameworks as related}
                                <span class="related-tag">{related}</span>
                              {/each}
                            </div>
                          </div>
                        {/if}
                      </div>
                    {/each}
                  </div>
                </div>
              {/each}
            {/if}
          </div>
          
          <div class="reports-section">
            <h3>分析报告</h3>
            <div class="report-links">
              <a href={getHtmlReportUrl()} target="_blank" class="report-button">
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"></path>
                  <polyline points="14 2 14 8 20 8"></polyline>
                  <line x1="16" y1="13" x2="8" y2="13"></line>
                  <line x1="16" y1="17" x2="8" y2="17"></line>
                  <polyline points="10 9 9 9 8 9"></polyline>
                </svg>
                HTML报告
              </a>
              <a href={getJsonReportUrl()} target="_blank" class="report-button">
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <rect x="2" y="3" width="20" height="14" rx="2" ry="2"></rect>
                  <line x1="8" y1="21" x2="16" y2="21"></line>
                  <line x1="12" y1="17" x2="12" y2="21"></line>
                </svg>
                JSON数据
              </a>
            </div>
          </div>
        </div>
      {/if}
    </div>
  {/if}
</div>

<!-- 删除确认对话框 -->
{#if showDeleteModal}
  <div class="modal-overlay">
    <div class="modal-container">
      <div class="modal-header">
        <h3>确认删除</h3>
        <button class="close-button" on:click={closeDeleteModal} disabled={isDeleting}>
          <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <line x1="18" y1="6" x2="6" y2="18"></line>
            <line x1="6" y1="6" x2="18" y2="18"></line>
          </svg>
        </button>
      </div>
      
      {#if deleteSuccess}
        <div class="modal-content success">
          <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="#4caf50" stroke-width="2">
            <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path>
            <polyline points="22 4 12 14.01 9 11.01"></polyline>
          </svg>
          <p>文件已成功删除！</p>
        </div>
      {:else}
        <div class="modal-content">
          <p>您确定要删除此任务的文件吗？</p>
          
          {#if deleteError}
            <div class="delete-error">
              <p>{deleteError}</p>
            </div>
          {/if}
          
          <div class="delete-options">
            <button class="delete-option" on:click={() => handleDelete(false)} disabled={isDeleting}>
              <span>仅删除上传文件</span>
              <small>保留分析报告数据</small>
            </button>
            
            <button class="delete-option delete-all" on:click={() => handleDelete(true)} disabled={isDeleting}>
              <span>删除所有文件</span>
              <small>包括分析报告和结果</small>
            </button>
          </div>
        </div>
      {/if}
      
      <div class="modal-footer">
        {#if !deleteSuccess}
          <button class="cancel-button" on:click={closeDeleteModal} disabled={isDeleting}>取消</button>
        {/if}
      </div>
    </div>
  </div>
{/if}

<style>
  .task-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 2rem;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen,
      Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
  }
  
  header {
    display: flex;
    flex-direction: column;
    margin-bottom: 2rem;
  }
  
  .back-link {
    margin-bottom: 1rem;
  }
  
  .back-link a {
    color: #4a90e2;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
  }
  
  .back-link a:hover {
    text-decoration: underline;
  }
  
  h1 {
    font-size: 2rem;
    margin: 0;
    color: #333;
  }
  
  .loading {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 3rem;
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
  
  .spinner {
    width: 40px;
    height: 40px;
    border: 4px solid rgba(0, 0, 0, 0.1);
    border-left-color: #4a90e2;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 1rem;
  }
  
  @keyframes spin {
    to { transform: rotate(360deg); }
  }
  
  .error-card {
    background-color: #fff3f3;
    border: 1px solid #ffcfcf;
    padding: 2rem;
    border-radius: 8px;
    text-align: center;
  }
  
  .error-card button {
    background-color: #4a90e2;
    color: white;
    border: none;
    padding: 0.75rem 1.5rem;
    border-radius: 4px;
    font-size: 1rem;
    cursor: pointer;
    margin-top: 1rem;
  }
  
  .task-card {
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    overflow: hidden;
  }
  
  .task-header {
    padding: 1.5rem;
    border-bottom: 1px solid #eee;
  }
  
  .task-meta {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    margin-top: 1rem;
    gap: 1rem;
  }
  
  .status-badge {
    padding: 0.25rem 0.75rem;
    border-radius: 1rem;
    font-size: 0.85rem;
    font-weight: 500;
  }
  
  .status-completed {
    background-color: #e0f7ea;
    color: #00a854;
  }
  
  .status-failed {
    background-color: #fff1f0;
    color: #f5222d;
  }
  
  .status-processing {
    background-color: #e6f7ff;
    color: #1890ff;
    animation: pulse 2s infinite;
  }
  
  .status-pending {
    background-color: #fff7e6;
    color: #fa8c16;
  }
  
  @keyframes pulse {
    0% { opacity: 1; }
    50% { opacity: 0.7; }
    100% { opacity: 1; }
  }
  
  .task-time {
    color: #888;
    font-size: 0.9rem;
  }
  
  .delete-button {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.4rem 0.8rem;
    background-color: #ff4d4f;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 0.9rem;
    margin-left: auto;
  }
  
  .delete-button:hover {
    background-color: #ff7875;
  }
  
  .progress-section {
    padding: 2rem;
    text-align: center;
  }
  
  .progress-bar {
    height: 8px;
    background-color: #f0f0f0;
    border-radius: 4px;
    margin-bottom: 1rem;
    overflow: hidden;
  }
  
  .progress-inner {
    height: 100%;
    background-color: #1890ff;
    border-radius: 4px;
    animation: progress 2s ease infinite;
    width: 30%;
  }
  
  @keyframes progress {
    0% { transform: translateX(-100%); }
    100% { transform: translateX(400%); }
  }
  
  .error-section {
    padding: 2rem;
    color: #f5222d;
  }
  
  .result-section {
    padding: 1.5rem;
  }
  
  .summary-section {
    margin-bottom: 2rem;
  }
  
  .summary-section pre {
    background-color: #f5f5f5;
    padding: 1rem;
    border-radius: 4px;
    overflow-x: auto;
    white-space: pre-wrap;
    font-family: monospace;
  }
  
  .frameworks-section {
    margin-bottom: 2rem;
  }
  
  .category-group {
    margin-bottom: 1.5rem;
  }
  
  .frameworks-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 1rem;
    margin-top: 0.5rem;
  }
  
  .framework-card {
    border: 1px solid #e8e8e8;
    border-radius: 4px;
    padding: 1rem;
    background-color: #f9f9f9;
  }
  
  .framework-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 0.5rem;
  }
  
  .framework-header h5 {
    margin: 0;
    font-size: 1.1rem;
  }
  
  .confidence-badge {
    padding: 0.2rem 0.5rem;
    border-radius: 4px;
    color: white;
    font-size: 0.85rem;
  }
  
  .framework-version {
    color: #666;
    font-size: 0.9rem;
    margin-bottom: 0.5rem;
  }
  
  .framework-description {
    font-size: 0.9rem;
    margin: 0.5rem 0;
    color: #333;
  }
  
  .related-frameworks {
    margin-top: 0.75rem;
    font-size: 0.9rem;
  }
  
  .related-list {
    display: flex;
    flex-wrap: wrap;
    gap: 0.4rem;
    margin-top: 0.3rem;
  }
  
  .related-tag {
    background-color: #e6f7ff;
    color: #1890ff;
    padding: 0.1rem 0.5rem;
    border-radius: 4px;
    font-size: 0.8rem;
  }
  
  .reports-section {
    margin-top: 2rem;
    padding-top: 1.5rem;
    border-top: 1px solid #eee;
  }
  
  .report-links {
    display: flex;
    gap: 1rem;
    margin-top: 1rem;
  }
  
  .report-button {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.75rem 1.5rem;
    background-color: #4a90e2;
    color: white;
    text-decoration: none;
    border-radius: 4px;
    font-weight: 500;
  }
  
  .report-button:hover {
    background-color: #3a80d2;
  }
  
  /* 模态框样式 */
  .modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
  }
  
  .modal-container {
    background-color: white;
    border-radius: 8px;
    width: 100%;
    max-width: 500px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
    overflow: hidden;
  }
  
  .modal-header {
    padding: 1rem 1.5rem;
    border-bottom: 1px solid #eee;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .modal-header h3 {
    margin: 0;
    color: #333;
  }
  
  .close-button {
    background: none;
    border: none;
    cursor: pointer;
    color: #888;
    padding: 0.25rem;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .close-button:hover {
    color: #333;
  }
  
  .modal-content {
    padding: 1.5rem;
  }
  
  .modal-content.success {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 2rem;
  }
  
  .modal-content.success svg {
    margin-bottom: 1rem;
  }
  
  .modal-content.success p {
    font-size: 1.1rem;
    font-weight: 500;
    color: #333;
  }
  
  .delete-error {
    background-color: #fff1f0;
    color: #f5222d;
    padding: 0.75rem;
    border-radius: 4px;
    margin: 1rem 0;
  }
  
  .delete-options {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 1rem;
    margin-top: 1rem;
  }
  
  .delete-option {
    display: flex;
    flex-direction: column;
    padding: 1rem;
    background-color: #f9f9f9;
    border: 1px solid #e8e8e8;
    border-radius: 4px;
    cursor: pointer;
    text-align: center;
  }
  
  .delete-option:hover {
    background-color: #f0f0f0;
  }
  
  .delete-option.delete-all {
    background-color: #fff1f0;
    border-color: #ffccc7;
  }
  
  .delete-option.delete-all:hover {
    background-color: #fff0f0;
  }
  
  .delete-option span {
    font-weight: 500;
    margin-bottom: 0.25rem;
  }
  
  .delete-option small {
    font-size: 0.8rem;
    color: #666;
  }
  
  .modal-footer {
    padding: 1rem 1.5rem;
    border-top: 1px solid #eee;
    display: flex;
    justify-content: flex-end;
  }
  
  .cancel-button {
    padding: 0.5rem 1.25rem;
    background-color: #f5f5f5;
    border: 1px solid #d9d9d9;
    border-radius: 4px;
    color: #333;
    cursor: pointer;
  }
  
  .cancel-button:hover {
    background-color: #e8e8e8;
  }
  
  .cancel-button:disabled {
    opacity: 0.6;
    cursor: not-allowed;
  }
  
  @media (max-width: 768px) {
    .task-container {
      padding: 1rem;
    }
    
    .frameworks-grid {
      grid-template-columns: 1fr;
    }
    
    .report-links {
      flex-direction: column;
    }
    
    .delete-options {
      grid-template-columns: 1fr;
    }
  }
</style> 
